<?php

namespace App\Http\Controllers\PC\Pay;

use Illuminate\Http\Request;
use Session,Config;
use App\Http\Requests;
use App\Http\Service\Product\ProductService;
use App\Http\Service\User\UserService;
use App\Http\Service\Pay\PayService;
use App\Http\Controllers\Controller;
require_once "phpqrcode.php";
use QRcode;
use App\Http\Service\Statistic\StatisticService;


class PayController extends Controller
{

    private $statistic;
    private $params = [];

    public function __construct(StatisticService $statistic)
    {
        header("Content-type:text/html;charset=utf-8");
        $this->statistic = new StatisticService();

    }
    public function index(Request $request)
    {
        $title='支付';

        $where = [];
        $where['pay_id'] = $request->input('pay_id');
        $product = new ProductService();
        $info = $product->getProductInfo($where);



        if($info['code'] == '0')
        {
            $data = $info['data'];
            if($data['info']['name'] == '')
            {
                return redirect('/buy');
            }

        }else{

            echo "<script>confirm('{$info['msg']}')?location.href='/' : history.back() ;</script>";
            exit();
        }

        if($data['info']['activity_flag'] == 1)
        {
            return view('PC.Pay.discount')->with('data',$data)->with('title',$title);
        }else{

            return view('PC.Pay.pay')->with('data',$data)->with('title',$title);
        }

    }



    //  生成订单信息
    public function createOrder(Request $request)
    {
        $where = [];
        $price = 0;
        $oder_no = '';
        $token = '';
        $order = [];
        $coupon_discount = 1;      //   默认折扣为1
        $month = 1;                 //   数量  默认为一
        $where['pay_type'] = $request->input('pay_type');
        $where['month'] = $request->input('month');
        $where['product'] = $request->input('product');


//
//        if(empty($where))
//        {
//            return view('welcome');
//        }

        //  支付类型判断
        if(!isset($where['pay_type']) || empty($where['pay_type']) || $where['pay_type'] != 'alipay' && $where['pay_type'] != 'wxpay')
        {
            $where['pay_type'] = 'alipay';
        }



        /**
         * 给用户充值
         */
        if(!empty($where['account']))
        {
            $user = new UserService();
            $user_id =  $user->accountGetUserId($where);
            $order['to_user'] = $user_id;
        }else{
            unset($where['account']);
        }

        /**
         *优惠码优惠
         */
//        if(!empty($where['code']))
//        {
//            $user = new UserService();
//            $coupon =  $user->discountCoupon($where);
//            if($coupon['code'] == '0')
//            {
//                $coupon_discount = $coupon['data']['coupon']['discount'];
//                $order['coupon_code'] = $where['code'];                //  优惠号码
//            }else{
//                unset($where['code']);
//            }
//
//        }else{
//            unset($where['code']);
//        }

        if($where['month'] >= 1 ){
            $month = $where['month'];
        }else{
            $where['month'] = $month;
        }

//dd($month);
        /**
         * 产品详情   价格
         */
        $product = new ProductService();

        if(!isset($where['product']))
        {

            return view('welcome');
        }

        $where['pay_id'] = $where['product'];
        unset($where['product']);


        $info = $product->getProductInfo($where);
        $price = $info['data']['info']['price_discount'];
        $vip = $info['data']['info']['type_id'];


        $token = Session::get(Config::get('custom.setting.MEMBER_TOKEN'));              //  获取用户的token

        //  生成订单号
        $order_no = self::createUuid();

        //   订单信息
        $order['order_no'] = $order_no;
        $order['token'] = $token;
        $order['price'] = $price * $coupon_discount * $month;            //  价格


        $order['pay_id'] = $where['pay_id'];

        $order['month'] = $month;
        $order['price_origin'] = $price * $month;
        $order['agent_id'] = 1;                                             //  牛魔科技   1
        $order['vip'] = $vip;                                             //  会员类型标识

        try{
            if(Session::get(Config::get('custom.setting.MEMBER_QUERY')))
            {
                $this->params['url'] = Session::get(Config::get('custom.setting.MEMBER_QUERY'));
                $this->params['code'] = Session::get(Config::get('custom.setting.MEMBER_UNQUIE_CODE'));

                $this->params['action'] = 'buy';    // 购买
                $this->params['terminal_id'] = 2;  //  PC端
                $this->params['status'] = '0';  //  状态
                $this->params['order_no'] = $order_no;  //  订单号
                $this->params['money'] = $order['price'];  //  订单号
                $this->params['ip'] = $request->getClientIp();  //  客户端IP
                $this->statistic->Statictis($this->params);
            }
        }catch (\Exception $exception){

        }

        $data = self::SlingPay($where['pay_type'],$order);


        if($where['pay_type'] == 'wxpay')
        {
            return QRcode::png($data['data']);

        }else{
            if(!$data['code']==0){
                echo $data['msg'];die();
            }else{
                return  $data['data'];
            }
        }
    }


    static function SlingPay($pay_type,$order)
    {
        $pay = new PayService();
        switch ($pay_type)
        {
            case 'alipay':return $data = $pay->SlingAliPay($order);break;
            case 'wxpay':return $data = $pay->SlingWxPay($order);break;
        }
    }


    /**
     * @param Request $request
     *检测微信扫码支付订单的状态
     */
    public function checkWxPayOrderStatus(Request $request)
    {
        $where = [];
        $where['token'] = Session::get(Config::get('custom.setting.MEMBER_TOKEN'));
        $where['product'] = $request->input('product');
        $pay = new PayService();
        $data = $pay->checkWxPayOrderStatus($where);
        return response()->json($data);
    }


    //可以指定前缀
    static function createUuid($prefix = "")
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid  = substr($str,0,8) . '-';
        $uuid .= substr($str,8,4) . '-';
        $uuid .= substr($str,12,4) . '-';
//        $uuid .= substr($str,16,4) . '-';
        $uuid .= substr($str,20,12);
        return $prefix . $uuid;
    }




}
